package com.leosoft.heatmonitor.service.transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import com.leosoft.heatmonitor.dao.UserDAO;
import com.leosoft.heatmonitor.model.Role;
import com.leosoft.heatmonitor.model.User;

@Component("myUserDetailsService")
public class MyUserDetailService implements UserDetailsService {
	@Autowired
	private UserDAO userDAO;

	private final ConcurrentHashMap<String, org.springframework.security.core.userdetails.User> cache = new ConcurrentHashMap<String, org.springframework.security.core.userdetails.User>();

	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		UserDetails currentUser = cache.get(username);
		if (currentUser == null) {
			User user = userDAO.getUserByName(username);
			List<Role> roles = user.getRoles();
			List<GrantedAuthority> roleList = new ArrayList<GrantedAuthority>();
			for (Role role : roles) {
				roleList.add(new SimpleGrantedAuthority(role.getRole()));
			}
			currentUser = new org.springframework.security.core.userdetails.User(user.getUsername(),
					user.getPassword(), true, true, true, true, roleList);
		}
		return currentUser;
	}
}
